<template>
    <div class="page-container">
        <!-- 按钮工具栏 -->
        <div class="button-toolbar">
            <el-button @click="goBack" icon="el-icon-back">返回</el-button>
            <span>
                <el-button type="primary" @click="saveData" :disabled="isView" icon="el-icon-check">保存</el-button>
            <el-button @click="goToList" icon="el-icon-menu">列表</el-button>
            <el-button type="success" @click="printToPDF" icon="el-icon-printer">打印PDF</el-button>
            </span>
        </div>

        <div class="certificate-container">
            <!-- 公司留存联 -->
            <div class="certificate">
                <div class="certificate-header">
                    <h2 class="title">离职证明</h2>
                    <div class="divider"></div>
                    <h3 class="subtitle">(公司留存联)</h3>
                </div>
                <div class="certificate-content">
                    <p class="content-paragraph">
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        兹证明 <el-input v-model="name" :disabled="isView" class="inline-input name-input"></el-input>
                        （身份证号码 <el-input v-model="idNumber" :disabled="isView" class="inline-input id-input"></el-input>），
                        原系我公司员工，于 
                        <el-date-picker
                            v-model="formData.entryDate"
                            type="date"
                            :disabled="isView"
                            value-format="yyyy-MM-dd"
                            format="yyyy年MM月dd日"
                            class="date-picker"
                            placeholder="选择入职日期">
                        </el-date-picker>
                        日入职，已于 
                        <el-date-picker
                            v-model="formData.leaveDate"
                            type="date"
                            :disabled="isView"
                            value-format="yyyy-MM-dd"
                            format="yyyy年MM月dd日"
                            class="date-picker"
                            placeholder="选择离职日期">
                        </el-date-picker>
                        日因 <el-input v-model="reason" :disabled="isView" class="inline-input reason-input"></el-input>，
                        现已与本公司终止劳动合同，在职期间曾担任本公司 
                        <el-input v-model="department" :disabled="isView" class="inline-input department-input"></el-input> 
                        部门 <el-input v-model="position" :disabled="isView" class="inline-input position-input"></el-input> 一职。
                    </p>
                    <p class="certificate-declaration">特此证明!</p>
                    <div class="signature-section">
                        <div class="signature-item">
                            <span>员工签名：</span>
                            <el-input v-model="formData.signature" :disabled="isView" class="signature-input"></el-input>
                        </div>
                        <div class="signature-item">
                            <span>领取日期：</span>
                            <el-date-picker
                                v-model="formData.receiveDate"
                                type="date"
                                :disabled="isView"
                                value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日"
                                class="date-picker"
                                placeholder="选择日期">
                            </el-date-picker>
                        </div>
                    </div>
                </div>
                <div class="certificate-footer">
                    <span>表单编号及版本：AM-JY-281 A/0</span>
                    <span>保存期限：长期</span>
                </div>
            </div>

            <!-- 员工联 -->
            <div class="certificate">
                <div class="certificate-header">
                    <h2 class="title">离职证明</h2>
                    <div class="divider"></div>
                    <h3 class="subtitle">(员工联)</h3>
                </div>
                <div class="certificate-content">
                    <p class="content-paragraph">
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        兹证明 <el-input v-model="name" :disabled="isView" class="inline-input name-input"></el-input>
                        （身份证号码 <el-input v-model="idNumber" :disabled="isView" class="inline-input id-input"></el-input>），
                        原系我公司员工，于 
                        <el-date-picker
                            v-model="formData.entryDate"
                            type="date"
                            :disabled="isView"
                            value-format="yyyy-MM-dd"
                            format="yyyy年MM月dd日"
                            class="date-picker"
                            placeholder="选择入职日期">
                        </el-date-picker>
                        日入职，已于 
                        <el-date-picker
                            v-model="formData.leaveDate"
                            type="date"
                            :disabled="isView"
                            value-format="yyyy-MM-dd"
                            format="yyyy年MM月dd日"
                            class="date-picker"
                            placeholder="选择离职日期">
                        </el-date-picker>
                        日因 <el-input v-model="reason" :disabled="isView" class="inline-input reason-input"></el-input>，
                        现已与本公司终止劳动合同，在职期间曾担任本公司 
                        <el-input v-model="department" :disabled="isView" class="inline-input department-input"></el-input> 
                        部门 <el-input v-model="position" :disabled="isView" class="inline-input position-input"></el-input> 一职。
                    </p>
                    <p class="certificate-declaration">特此证明!</p>
                    <div class="signature-section">
                        <div class="signature-item">
                            <el-input v-model="formData.companyName" :disabled="isView" class="company-input"></el-input>
                            <span>有限公司</span>
                        </div>
                        <div class="signature-item">
                            <el-date-picker
                                v-model="formData.issueDate"
                                type="date"
                                :disabled="isView"
                                value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日"
                                class="date-picker"
                                placeholder="选择日期">
                            </el-date-picker>
                        </div>
                    </div>
                </div>
                <div class="certificate-footer">
                    <span>表单编号及版本：AM-JY-281 A/0</span>
                    <span>保存期限：长期</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { getResignationCertificateById, saveResignationCertificate } from '@/api/resignationCertificate'

export default {
    data() {
        return {
            isView: false,
            formData: {
                id: null,
                name: '',
                idNumber: '',
                entryDate: '',
                leaveDate: '',
                reason: '',
                department: '',
                position: '',
                signature: '',
                receiveDate: '',
                issueDate: '',
                companyName: ''
            }
        };
    },
    computed: {
        // 公司留存联和员工联共用的计算属性
        name: {
            get() {
                return this.formData.name;
            },
            set(value) {
                this.formData.name = value;
            }
        },
        idNumber: {
            get() {
                return this.formData.idNumber;
            },
            set(value) {
                this.formData.idNumber = value;
            }
        },
        reason: {
            get() {
                return this.formData.reason;
            },
            set(value) {
                this.formData.reason = value;
            }
        },
        department: {
            get() {
                return this.formData.department;
            },
            set(value) {
                this.formData.department = value;
            }
        },
        position: {
            get() {
                return this.formData.position;
            },
            set(value) {
                this.formData.position = value;
            }
        }
    },
    created() {
        const { id, type } = this.$route.query;
        if (id) {
            this.fetchData(id);
        }
        this.isView = type === 'view';
    },
    methods: {
        goToList(){
            this.$router.push('/main/renshi/renshizhidu/lizhizm/lizhizmList');
        },
        goBack(){
            this.$router.push('/main/renshi/renshidiaodong/yuangonglizhi/yuangonglizhi');
        },
        fetchData(id) {
            getResignationCertificateById(id).then(response => {
                const data = response.data;
                // 格式化日期
                const formatDate = (dateStr) => {
                    if (!dateStr) return '';
                    const date = new Date(dateStr);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                };

                this.formData = {
                    id: data.id,
                    name: data.employeeName,
                    idNumber: data.idNumber,
                    entryDate: formatDate(data.entryDate),
                    leaveDate: formatDate(data.leaveDate),
                    reason: data.leaveReason,
                    department: data.department,
                    position: data.position,
                    signature: data.employeeSignature,
                    receiveDate: formatDate(data.receiveDate),
                    issueDate: formatDate(data.issueDate),
                    companyName: data.companyName
                };
            });
        },
        validateForm() {
            if (!this.formData.name) {
                this.$message({
                    type: 'warning',
                    message: '请输入员工姓名'
                });
                return false;
            }
            if (!this.formData.idNumber) {
                this.$message({
                    type: 'warning',
                    message: '请输入身份证号码'
                });
                return false;
            }
            if (!this.formData.entryDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择入职日期'
                });
                return false;
            }
            if (!this.formData.leaveDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择离职日期'
                });
                return false;
            }
            if (new Date(this.formData.leaveDate) < new Date(this.formData.entryDate)) {
                this.$message({
                    type: 'warning',
                    message: '离职日期不能早于入职日期'
                });
                return false;
            }
            return true;
        },
        saveData() {
            if (!this.validateForm()) {
                return;
            }
            
            const data = {
                id: this.formData.id,
                employeeName: this.formData.name,
                idNumber: this.formData.idNumber,
                entryDate: this.formData.entryDate,
                leaveDate: this.formData.leaveDate,
                leaveReason: this.formData.reason,
                department: this.formData.department,
                position: this.formData.position,
                employeeSignature: this.formData.signature,
                receiveDate: this.formData.receiveDate,
                issueDate: this.formData.issueDate,
                companyName: this.formData.companyName
            };
            
            saveResignationCertificate([data]).then(() => {
                this.$message({
                    type: 'success',
                    message: '保存成功！'
                });
                this.$router.push('/main/renshi/renshizhidu/lizhizm/lizhizmList');
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '保存失败：' + error.message
                });
            });
        },
        printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.querySelector('.certificate-container');
            html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 522;
                const pageHeight = 841.89;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                let positionY = 0;
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight;
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight);
                        positionY += pageHeight;
                        doc.addPage();
                        leftHeight -= pageHeight;
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight);
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
                }
                doc.save('离职证明.pdf');
            });
        }
    }
};
</script>

<style scoped>
.page-container {
    padding: 20px;
    /* background-color: #f5f7fa; */
    min-height: 100vh;
    font-family: '宋体';
    
}

.button-toolbar {
    width: 970px;
    margin: 0 auto;
    margin-bottom: 20px;
    padding: 16px;
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
}

.certificate-container {
    max-width: 1000px;
    margin: 0 auto;
}

.certificate {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 30px;
    margin-bottom: 30px;
}

.certificate-header {
    text-align: center;
    margin-bottom: 30px;
}

.title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 15px;
}

.divider {
    height: 2px;
    background-color: #000;
    margin: 15px auto;
    width: 100%;
}

.subtitle {
    font-size: 20px;
    margin-top: 15px;
}

.certificate-content {
    font-size: 16px;
    line-height: 2;
    margin: 20px 0;
}

.content-paragraph {
    /* text-indent: 2em; */
    margin-bottom: 20px;
    text-align: left;
}

.inline-input {
    display: inline-block;
    width: auto;
    margin: 0 5px;
}

.name-input {
    width: 120px;
}

.id-input {
    width: auto;
}

.reason-input {
    width: 150px;
}

.department-input {
    width: 120px;
}

.position-input {
    width: 120px;
}

.date-picker {
    width: auto;
}

.certificate-declaration {
    margin: 20px 0;
    font-weight: bold;
}

.signature-section {
    display: flex;
    justify-content: flex-end;
    margin-top: 30px;
    gap: 20px;
}

.signature-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.signature-input {
    width: 150px;
}

.company-input {
    width: 200px;
}

.certificate-footer {
    margin-top: 30px;
    display: flex;
    justify-content: space-between;
    color: #909399;
    font-size: 14px;
}

::v-deep .el-input__inner{
    border: none;
}

:deep(.el-input__inner) {
    border: none;
    /* border-bottom: 1px solid #dcdfe6; */
    border-radius: 0;
}

:deep(.el-input__inner:focus) {
    border-bottom-color: #409EFF;
}

:deep(.el-input.is-disabled .el-input__inner) {
    background-color: transparent;
    /* border-bottom: 1px dashed #dcdfe6; */
}
</style>